'use strict';

const db = uniCloud.database();
const userCollection = db.collection('xxf-users');

const {
	getToken,
	verifyToken
} = require('wx-common'); // 生成token和校验token公共模块
const configCenter = require("uni-config-center");
var wxConfig = configCenter({
	pluginId: 'wx-login'
}).requireFile('config.js'); // 读取配置中心配置

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event);
	const {
		action
	} = event;
	switch (action) {
		case 'wxLogin':
			return wxLogin(event);
		case 'wxVerifyToken':
			return wxVerifyToken(event);
		case 'wxDecryptData':
			return wxDecryptData(event);
		case 'uploadShoppingInfoToWx':
			return uploadShoppingInfoToWx(event);

		default:
			return {
				msg: 'Invalid action！',
					code: 0,
					data: null
			};
	}
};
async function uploadShoppingInfoToWx(params) {
	const {
		token,
		order_key,
		shipping_list,
		payer
	} = params;
	const infoRes = await uniCloud.httpclient.request(
		// `https://api.weixin.qq.com/user-order/orders?access_token=${token}`,
		`https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=${token}`, {
			method: 'POST',
			data: {
				upload_time: Date.now(),
				logistics_type: 1,
				delivery_mode: 'UNIFIED_DELIVERY',
				order_key,
				payer,
				shipping_list,
			},
			contentType: 'json',
			dataType: 'json'
		}
	);
	console.log("infoRes: ", infoRes);

}

async function wxDecryptData(params) {
	const {
		code,
		token,
	} = params;
	if (!code) {
		return;
	}
	const tokenRes = await uniCloud.httpclient.request(
		`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxConfig.appId}&secret=${wxConfig.secret}`, {
			method: 'GET',
			dataType: 'json'
		}
	);
	console.log("tokenRes: ", tokenRes);
	const access_token = tokenRes.data.access_token;
	console.log("access_token: ", access_token);
	console.log("code: ", code);
	const decryptRes = await uniCloud.httpclient.request(
		`https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${access_token}`, {
			method: 'POST',
			data: {
				code: code,
			},
			contentType: 'json',
			dataType: 'json'
		});
	console.log("decryptRes: ", decryptRes);
	if (decryptRes.status === 200) {
		if (decryptRes.data && decryptRes.data.phone_info && decryptRes.data.phone_info.phoneNumber) {
			return {
				msg: 'SUCCESS！',
				code: 1,
				data: decryptRes.data.phone_info.phoneNumber
			}
		} else {
			return {
				msg: 'FAIL！',
				code: 1,
				data: ""
			}
		}
	} else {
		return {
			msg: '获取微信手机号失败！',
			code: 2,
			data: null
		}
	}
}

async function wxVerifyToken(params) {
	const {
		token,
	} = params;
	if (token) {
		// 验证token
		const verifyRes = verifyToken(token);
		console.log("verifyRes: ", verifyRes);
		if (verifyRes) {
			return {
				msg: 'success！！',
				code: 1,
				data: true
			}
		} else {
			return {
				msg: 'fail！！',
				code: 1,
				data: false
			}
		}
	} else {
		return {
			msg: 'fail！！',
			code: 1,
			data: false
		}
	}
}

async function wxLogin(params) {
	const {
		code,
	} = params;
	// 获取用户openid和session_key
	const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/sns/jscode2session', {
		method: 'GET',
		data: {
			js_code: code, // 客户端传递过来的code
			appid: wxConfig.appId,
			secret: wxConfig.secret,
			grant_type: 'authorization_code'
		},
		dataType: 'json'
	});
	// 判断请求用户openid和session_key是否成功
	if (res.status === 200) {
		//成功返回的openid和session_key
		const wx_openid = res.data.openid
		const wx_session_key = res.data.session_key
		// 生成token
		const token = getToken(wx_openid);
		console.log("wxLogin getToken: ", token);
		//查询数据库判断用户是否已经注册 根据openid查找
		const userRes = await userCollection.where({
			open_id: wx_openid
		}).get()
		console.log("wxLogin userRes: ", userRes);
		//用户未注册存储用户信息
		if (userRes.data && userRes.data.length === 0) {
			const createRes = await uniCloud.callFunction({
				name: 'xxf-user',
				data: {
					action: "createUser",
					token: token,
					open_id: wx_openid,
					session_key: wx_session_key,
					create_time: Date.now(),
					latest_login_time: Date.now(),
					update_time: Date.now(),
				}
			});
			console.log("login createRes: ", createRes);
			return createRes.result;
		} else if (userRes.data && userRes.data.length === 1) {
			const user = userRes.data[0];
			// 用户已经存在更新token和session_key 
			const updateRes = await uniCloud.callFunction({
				name: 'xxf-user',
				data: {
					action: "updateUser",
					uid: user._id,
					token: token,
					session_key: wx_session_key,
					latest_login_time: Date.now(),
					update_time: Date.now(),
				}
			});
			console.log("login updateRes: ", updateRes);
			return updateRes.result;
		} else {
			return {
				msg: '用户数据异常！',
				code: 0,
				data: null
			}
		}
	} else {
		return {
			msg: '获取微信服务失败！',
			code: 0,
			data: null
		}
	}
}